package pl.squeaky.mvc.view;

import org.eclipse.core.resources.IFile;
import org.eclipse.dltk.core.IMethod;
import org.eclipse.dltk.core.ISourceRange;
import org.eclipse.dltk.core.ModelException;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

import pl.squeaky.mvc.model.IAction;
import pl.squeaky.mvc.model.IController;
import pl.squeaky.mvc.model.IModel;
import pl.squeaky.mvc.model.IView;

public class MvcExplorerDoubleClickListener implements IDoubleClickListener {

	@Override
	public void doubleClick(DoubleClickEvent event) {
		ISelection selection = event.getSelection();
		if(selection instanceof IStructuredSelection) {
			IStructuredSelection structuredSelection = (IStructuredSelection)selection;
			Object element = structuredSelection.getFirstElement();
			
			ISelection textSelection = null;
			IFile file = null;
			if(element instanceof IController) {
				IController controller = (IController)element;
				file = controller.getFile();
			} else if(element instanceof IAction) {
				IAction action = (IAction)element;
				IMethod method = action.getMethod();
				ISourceRange range;
				try {
					range = method.getNameRange();
				} catch (ModelException e) {
					throw new RuntimeException(e);
				}
				
				textSelection = new TextSelection(range.getOffset(), range.getLength());
				try {
					file = (IFile)method.getUnderlyingResource();
				} catch (ModelException e) {
					throw new RuntimeException(e);
				}
			} else if(element instanceof IModel) {
				IModel model = (IModel)element;
				file = model.getFile();
			} else if(element instanceof IView) {
				IView view = (IView)element;
				file = view.getFile();
			}
			
			IEditorPart part = null;
			if(file != null) {
				IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
				
				try {
					part = IDE.openEditor(page, file, true);
				} catch (PartInitException e) {
					throw new RuntimeException(e);
				}
			}
			
			if(textSelection != null) {
				part.getEditorSite().getSelectionProvider().setSelection(textSelection);
			}
		}
	}

}
